package com.ebei.platform.common.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
@WebFilter(urlPatterns = { "/api/*" }, filterName = "crossFilter")
public class CrossFilter implements Filter {
	private String path = null;
    protected static List<String> passUrlList; // 路径集合，集合中的路径用于表示放行
    @Override
    public void destroy() {
    	path = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpresponse = (HttpServletResponse) response;
        HttpServletRequest httprequest = (HttpServletRequest) request;
        // 如果要做细的限制，仅限某域名下的可以进行跨域访问到此，可以将*改为对应的域名。
        httpresponse.setHeader("Access-Control-Allow-Origin", "*");
        httpresponse.setHeader("Access-Control-Allow-Methods", "*");
        httpresponse.setHeader("Access-Control-Max-Age", "1728000");
        httpresponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpresponse.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Content-Encoding,Content-Length");
        boolean checkResult = doPassUrlCheck(request,response);
        if(checkResult){
        	chain.doFilter(request, response);
        }else{
            JSONObject isTokenPass = TokenValidUtil.isTokenPass(httprequest);
            if (isTokenPass.containsKey("ErrorCode") && "0".equals(isTokenPass.getString("ErrorCode"))) {
                chain.doFilter(request, response);
            } else{
                JSONObject result = new JSONObject();
                result.put("ErrorCode", isTokenPass.getString("ErrorCode"));
                result.put("ErrorMessage", isTokenPass.getString("ErrorMessage"));
                result.put("Data",isTokenPass.getString("Data"));
                writerMessage(response, JSONObject.toJSONString(result));
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	path = filterConfig.getServletContext().getContextPath();
    	if(passUrlList == null){
    		passUrlList = new ArrayList<String>();
    	}
    }
    
    private void writerMessage(ServletResponse response, String jsonString) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();
    }
    
    private boolean doPassUrlCheck(ServletRequest request, ServletResponse response) {
    	boolean checkResult = false;
    	if(path == null){
            path = ((HttpServletRequest)request).getContextPath();
        }
    	String urls = ((HttpServletRequest)request).getRequestURI().toString();
    	if(passUrlList != null && passUrlList.size() >0){
    		for(String s : passUrlList){
    		    if(urls.indexOf(s)>0 || urls.endsWith(s.replace("*", ""))){
    				checkResult = true;
    				break;
    			}
        	}
    	}
    	
    	return checkResult;
    }
}
